#include <QDataStream>
#include <QComboBox>
#include "ItemFlag.h"
#include "ItemOption.h"

#include <cassert>


void ItemOption::setItemFlag(ItemFlag *flag)
{
    if (m_itemFlag)
        disconnect(m_itemFlag, &ConfigItem::itemEdited, this, &ItemOption::onFlagsEdited);
    m_itemFlag = flag;
    connect(m_itemFlag, &ConfigItem::itemEdited, this, &ItemOption::onFlagsEdited, Qt::QueuedConnection); // 放入事件队列，延时执行，让 ItemFlag 先更新，ItemOption 后更新
    m_enum = flag->getMetaEnum();
    onFlagsEdited();
}

void ItemOption::setComboBoxItems(QComboBox *comboBox)
{
    assert(m_itemFlag);

    int pre_option = m_option;

    blockSignals(true);

    if (comboBox)
    {
        comboBox->clear();
        QList<int> options = m_itemFlag->get().values();
        bool isMyOptionExist = false;
        for (int i = 0; i < options.count(); i++)
        {
            comboBox->addItem(tr(m_enum.valueToKey(options[i])), options[i]);
            if (m_option == options[i])
            {
                isMyOptionExist = true;
                // comboBox->setCurrentIndex(i);
            }
        }
        if (options.isEmpty())
        {
            m_option = -1;
        }
        else
        {
            if (!isMyOptionExist)
            {
                m_option = options[0];
                comboBox->setCurrentIndex(0);
            }
            else
            {
                comboBox->setCurrentIndex(comboBox->findData(m_option));
            }

        }
        //qInfo() << m_option;
    }

    blockSignals(false);

    if (pre_option != m_option)
        emit itemEdited();
}

QWidget *ItemOption::createWidget(ConfigItem::WidgetStyle s)
{
    auto w = new QComboBox;
    setComboBoxItems(w);
    connect(w, QOverload<int>::of(&QComboBox::currentIndexChanged), this, &ItemOption::onWidgetEditedWrapper);
    return w;
}

void ItemOption::update(QWidget *widget, UpdateOption option)
{
    QComboBox *comboBox = qobject_cast<QComboBox *>(widget);
    if (comboBox != nullptr)
    {
        if (option == UpdateOption::WidgetContent)
        {
            comboBox->setCurrentIndex(comboBox->findData(m_option));
        }
        else if (option == UpdateOption::Item)
        {
            m_option = comboBox->currentData().toInt();
        }
    }
    else
    {
        qWarning() << "";
    }
}

void ItemOption::writeToData(QDataStream &stream) const
{
    stream << qint32(m_option);
}

void ItemOption::readFromData(QDataStream &stream)
{
    qint32 temp;
    stream >> temp;
    m_option = temp;
    emit itemEdited();
}

void ItemOption::onFlagsEdited()
{
    for (auto w : relatedWidgets)
    {
        setComboBoxItems(qobject_cast<QComboBox *>(w));
    }
}

